/**
 * Created by shawn on 17/9/11.
 */
const db = {};
const mysql = require('mysql');
const config = require('../config/config');
const pool = mysql.createConnection(config.environment.development.dev);
const prefix = config.environment.development.dev.prefix;

db.query = function (table, field, where, callback) {
    if (!table) {
        callback();
        return;
    }
    var _WHERE = '';
    for (let k in where) {
        _WHERE += k + "='" + where[k] + "' AND "
    }
    var sql = "select " + field + " from " + prefix + table + " where " +_WHERE+ ' 1=1 ';
    pool.query(sql, function (err, result) {
        if (err) {
            console.log(err);
            callback(err, null);
            return;
        };
        callback(null, result);
    });
}

db.insert = function (table, obj, callback) {
    if (!obj) {
        callback();
        return;
    }
    var fields = '';
    var values = '';
    for (var k in obj) {
        fields += k + ',';
        values = values + "'" + obj[k] + "',"
    }
    fields = fields.slice(0, -1);
    values = values.slice(0, -1);
    var sql = "INSERT INTO " + prefix + table + '(' + fields + ') VALUES(' + values + ')';
    pool.query(sql, function (err, result) {
        if (err) {
            console.log('[INSERT ERROR] - ', err.message);
            callback(err, null);
            return;
        }
        callback(null, result)
    });
}

db.update = function (table, sets, where, callback) {
    if (!table) {
        callback()
        return;
    }
    var _SETS = '';
    var _WHERE = '';
    var keys = '';
    var values = '';
    for (var k in sets) {
        _SETS += k + "='" + sets[k] + "',";
    }
    _SETS = _SETS.slice(0, -1);
    for (var k2 in where) {
        _WHERE += k2 + "='" + where[k2] + "' AND ";
    }

    var sql = "UPDATE " + prefix + table + ' SET ' + _SETS + ' WHERE ' + _WHERE + ' 1=1 ';
    console.log('sql', sql);
    // //update table set username='admin2',age='55'   where id="5";
    pool.query(sql, function (err, result) {
        if (err) {
            console.log('[UPDATE ERROR] - ', err.message);
            callback(err, null);
            return;
        }
        ;
        callback(null, result);
    });
}

db.delete = function (table, where, callback) {
    var _WHERE = '';
    for (var k in where) {
        _WHERE += k + "='" + where[k] + "' AND ";
    }
    var sql = "DELETE  FROM " + prefix + table + ' WHERE ' + _WHERE + ' 1=1 ';

    console.log(sql);
    pool.query(sql, function (err, result) {
        if (err) {
            console.log('[DELETE ERROR] - ', err.message);
            callback(err, null)
            return;
        }
        callback(null, result);
    });

}

module.exports = db;

